from flask import Flask, request, redirect, url_for, flash, render_template
from werkzeug.utils import secure_filename
import os



app = Flask(__name__)

# 配置CSRF保护
app.secret_key = 'your_secret_key'

# 设置文件上传的最大大小（以字节为单位）
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024  # 最大上传文件为 16MB

# 定义上传文件的目录
UPLOAD_FOLDER = 'uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

# 允许上传的文件类型
ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'}


def allowed_file(filename):
    """检查文件是否为允许上传的类型"""
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


@app.route('/')
def upload_form():
    """返回上传文件的表单页面"""
    return render_template('upload.html')


@app.route('/upload', methods=['POST'])
def upload_file():
    """处理文件上传"""
    if 'file' not in request.files:
        flash('没有文件部分')
        return redirect(request.url)

    file = request.files['file']

    if file.filename == '':
        flash('没有选择文件')
        return redirect(request.url)

    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)  # 安全处理文件名
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))  # 保存文件
        return '文件上传成功'

    flash('不允许的文件类型')
    return redirect(request.url)


if __name__ == '__main__':
    if not os.path.exists(UPLOAD_FOLDER):
        os.makedirs(UPLOAD_FOLDER)  # 如果目录不存在则创建
    app.run(debug=True)
